package com.cdu.guoxinan.www.smartcom.aop;
import com.cdu.guoxinan.www.smartcom.aop.Annotation.OperationLog;
import com.cdu.guoxinan.www.smartcom.unit.Data.OperationLogRecord;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;

@Aspect
@Component
public class OperationLogAspect {
    @Resource
    private OperationLogService logService;

    @Around("@annotation(operationLog)")
    public Object logOperation(ProceedingJoinPoint joinPoint, OperationLog operationLog) throws Throwable {
        // 1. 创建日志记录
        OperationLogRecord logRecord = new OperationLogRecord();
        logRecord.setDescription(operationLog.description());
        logRecord.setOperateTime(new Date());
        logRecord.setUserId(logService.getCurrentUserId());
        // 4. 执行目标方法并记录结果
        try {
            Object result = joinPoint.proceed();
            logRecord.setSuccess("成功");
            return result;
        } catch (Throwable e) {
            logRecord.setSuccess("失败");
            logRecord.setErrorMsg(e.getMessage() != null ? (e.getMessage().length() > 255 ? e.getMessage().substring(0, 255) : e.getMessage()) : "未知错误");
            throw e;
        } finally {
            // 5. 异步保存日志
            logService.saveLog(logRecord);
        }
    }
}